{% extends 'base.html' %}
{% load staticfiles %}

{% block right_content %}
    <div class="row">
        <div class="col-md-12">
            <div class="box box-info">
                <div class="box-header">
                    <div class="mailbox-read-info">
                        <h3 class="box-title"><i class="fa fa-code"></i> <span
                                class="text-red">历史工单_{{ envi_name }}</span></h3>
                    </div>
                    <div id="s_envi_id" style="display:none;">{{ envi_id }}</div>
                </div>
                <div class="box-body">
                    <table id="demo-table"></table>
                </div>
            </div>
        </div>
    </div>

    <!-- 任务进度模态框 -->
    <div class="modal fade" id="modal_tasks_show" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span>
                    </button>
                    <h5>
                        <small><cite>
                            <i class="fa fa-check" style="color: green"></i>: 表示已经执行，
                            <i class="fa fa-close" style="color: red"></i>: 表示未推到该环境，
                            其他状态: 表示当前工单的进度
                        </cite></small>
                    </h5>
                </div>

                <div class="modal-body">
                    <div class="row">
                        <div class="box-body">
                            <table id="tasks-table"></table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 钩子模态框 -->
    <div class="modal fade" id="hook_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form class="form-horizontal" id="hook_form" action="{% url 'p_hook_sql_orders' %}"
                      method="post">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title"><i class="fa fa-magnet"></i> 请选择需要勾到环境的库名
                        </h4>
                    </div>

                    <div class="modal-body">
                        <div class="row">
                            <div class="form-group" style="display: none">
                                <label class="control-label col-md-2 col-sm-2 col-xs-12">id</label>
                                <div class="col-sm-8">
                                    <input title="" type="text" id="s_id" class="form-control" name="id">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="control-label col-sm-2 col-sm-2 col-xs-12">库名*</label>
                                <div class="col-sm-8">
                                    <select id="s_schema" name="database" style="width: 100%" required
                                            class="form-control selectpicker" title="选择库名..."
                                            data-live-search="true">
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary">提交</button>
                    </div>
                    {% csrf_token %}
                </form>
            </div>
        </div>
    </div>
{% endblock %}

{% block link_javascripts %}
    <script>
        /**
         * 初始化bootstrap-table，生成表格
         */
        let envi_id = $('#s_envi_id').text();
        $(function () {
            let $table = $('#demo-table');
            $table.bootstrapTable({
                method: 'get',
                dataType: 'json',
                contentType: "application/x-www-form-urlencoded",
                url: "{% url 'p_get_sql_orders_list' %}",
                cache: false,
                queryParams: function (params) {
                    return {
                        envi_id: envi_id,
                        limit_size: params.limit + params.offset,
                        offset_size: params.offset,
                        search_content: params.search
                    }
                },
                sidePagination: "server",
                showColumns: true,
                pagination: true,
                search: true,
                showRefresh: true,
                singleSelect: true,
                minimumCountColumns: 2,
                pageNumber: 1,
                pageSize: 10,
                locale: 'zh-CN',
                pageList: [10, 20],
                uniqueId: "id",
                rowStyle: render_row_style,
                classes: 'table table-hover table-no-bordered',

                columns: [
                    {
                        field: 'progress_value',
                        title: '进度',
                        formatter: function (value, row) {
                            return "<button type='button' class='btn " + row.progress_color + " btn-sm'>" + value + "</button>"
                        }
                    },
                    {
                        field: 'title',
                        title: '标题',
                        formatter: function (value, row) {
                            if (value.length >= 16) {
                                return '<a href="/sqlorders/sql_orders_details/' + row.id + '" title=\"' + value + '\">' + value.slice(0, 16) + '</a>'
                            }
                            else {
                                return '<a href="/sqlorders/sql_orders_details/' + row.id + '" title=\"' + value + '\">' + value + '</a>'
                            }
                        }
                    },
                    {
                        field: 'sql_type',
                        title: '类型'
                    },
                    {
                        field: 'remark',
                        title: '备注'
                    },
                    {
                        field: 'task_version',
                        title: '任务',
                        formatter: function (value) {
                            return "<a href='#' onclick='deploy_tasks_table(" + "\"" + value + "\"" + ")'>" + value + "</a>"
                        }
                    },
                    {
                        field: 'host',
                        title: '主机/库',
                        formatter: function (value, row) {
                            return value + ':' + row.port + '<br>' + row.database
                        }
                    },
                    {
                        field: 'proposer',
                        title: '申请人'
                    },
                    {
                        field: 'auditor',
                        title: '审批人'
                    },
                    {
                        field: 'created_at',
                        title: '提交时间',
                        formatter: function (value) {
                            return moment(value).format('YYYY-MM-DD HH:mm:ss');
                        }
                    },
                    {
                        field: 'approve',
                        title: '审批',
                        formatter: function (value, row) {
                            return "<a href='#' onclick='sql_orders_audit(" + row.id + "," + '\"/sqlorders/sql_orders_approve/\"' + ",\"通过\", \"不通过\")'><i class='fa fa-pencil-square-o fa-lg'></i></a>"
                        }
                    },
                    {
                        field: 'execute',
                        title: '执行',
                        formatter: function (value, row) {
                            return "<a href='#' onclick='general_perform_tasks(" + row.id + "," + row.envi_id + ")'><i class='fa fa-check-square-o fa-lg'></i></a>"
                        }
                    },
                    {
                        field: 'id',
                        title: '钩子',
                        formatter: function (value, row) {
                            return "<a href='#' type='button' data-toggle='modal' data-target='#hook_modal' data-whatever_id=\"" + row.id + "\"><i class='fa fa-magnet fa-lg'></i></a>"
                        }
                    },
                    {
                        field: 'feedback',
                        title: '反馈',
                        formatter: function (value, row) {
                            return "<a href='#' onclick='sql_orders_audit(" + row.id + "," + '\"/sqlorders/sql_orders_feedback/\"' + ",\"处理中\", \"已完成\")'><i class='fa fa-mail-reply-all fa-lg'></i></a>"
                        }
                    },
                    {
                        field: 'id',
                        title: '关闭',
                        formatter: function (value, row) {
                            return "<a href='#' onclick='sql_orders_audit(" + row.id + "," + '\"/sqlorders/sql_orders_close/\"' + ",\"提交\", \"结束\")'><i class='fa fa-close fa-lg'></i></a>"
                        }
                    }
                ],

                onLoadSuccess: function (value) {
                    // 权限视图隐藏
                    // 此处即使可以看见，后台也有权限进行控制
                    if (value.total > 0) {
                        let view_permission = value.rows[0].permissions;
                        if (view_permission.indexOf('can_audit_sql') < 0) {
                            // 隐藏审批权限的显示
                            $('#demo-table').bootstrapTable('hideColumn', 'approve')
                        }
                        if (view_permission.indexOf('can_execute_sql') < 0) {
                            // 隐藏执行和反馈权限的显示
                            $table.bootstrapTable('hideColumn', 'execute');
                            $table.bootstrapTable('hideColumn', 'feedback')
                        }
                    }
                }
            })
        });
        /**
         * 每3s刷新一次表格
         */

        $(function () {
            function refreshTable() {
                $('#demo-table').bootstrapTable('refresh', {silent: true});
            }

            setInterval(refreshTable, 3000);
        });

        /**
         * 获取当前环境的父环境的schema列表
         */
        $(function () {
            let csrftoken = $.cookie('csrftoken');
            $.ajax({
                url: '{% url 'p_get_parent_schemas' %}',
                type: 'POST',
                dataType: 'json',
                data: {'envi_id': envi_id, 'csrfmiddlewaretoken': csrftoken},
                timeout: 5000,
                cache: false,
                success: function (data) {
                    let html = '';
                    $.each(data, function (index, row) {
                        let result = [row.host, row.port, row.schema].join(',');
                        let show_result = [row.comment, row.port, row.schema].join('_');
                        html += "<option data-icon='fa fa-database' value=" + result + ">" + show_result + "</option>"
                    });
                    $('#s_schema').append(html);
                    $('.selectpicker').selectpicker('refresh')
                }
            })
        });

        /**
         * 提交钩子数据
         */

        let hook_modal_selector = $('#hook_modal');

        $('#hook_form').submit(function () {
            $(this).ajaxSubmit({
                dataType: 'json',
                resetForm: true,
                data: {'envi_id': envi_id},
                success: function (result) {
                    hook_modal_selector.modal('hide');
                    if (result.status === 0) {
                        window.parent.location.href = result.jump_url
                    } else {
                        displayPNotify(result.status, result.msg);
                    }
                },
                error: function (jqXHR) {
                    if (jqXHR.status === 403) {
                        hook_modal_selector.modal('hide');
                        displayPNotify(jqXHR.status);
                    }
                }
            });
            return false
        });

        <!-- 当模态框打开时 -->
        hook_modal_selector.on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget);
            // 获取值
            let recipient_id = button.data('whatever_id');
            let modal = $(this);
            let id = $('.modal-body input')[0];
            modal.find(id).val(recipient_id);
        });

        <!-- 当模态框关闭时 -->
        hook_modal_selector.on('hidden.bs.modal', function (event) {
            $('.selectpicker').selectpicker('refresh')
        })

        /**
         * 渲染行的样式
         * 已完成的自动标记为：绿色(success)
         * 关闭的自动标记为：红色(danger)
         */
        function render_row_style(row, index) {
            let finish_status = ['已完成', '已关闭', '已勾住'];
            if (finish_status.indexOf(row.progress_value) < 0) {
                return {classes: 'danger'}
            } else {
                return {};
            }
        }
    </script>
{% endblock %}